<script setup lang="ts">
import { computed, ref, reactive, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getAddressListAPI } from '@/services/settingApi'
import type { addressType } from '@/types/settings'
import { useAddressStore } from '@/stores/modules/addressStore'
import type { sku_order_data_type } from '@/types/sku'
import { useCartStore } from '@/stores/modules/CartStore'
import { getSkuByIdApi, getSkuByOrderNumberAPI } from '@/services/skuAPI'
import type { post_order_info_item_info } from '@/types/order'
import { createOrderApi } from '@/services/orderApi'
// 订单号列表，用于传递给订单详情页，从而获取数据
const params = defineProps<{
  num: number
  order_number: string
  sku_id_list: number[]
}>()

// 获取屏幕边界到安全区域距离
const systemInfo = reactive({
  safeAreaInsets: {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
  },
})
const skuOrderData = ref<sku_order_data_type[]>([])
const addressStore = useAddressStore()
const addressListData = ref<addressType[]>()
// 订单备注
const post_order_info = ref<post_order_info_item_info[]>([])
// 配送时间
const deliveryList = ref([
  { type: 0, text: '时间不限 (周一至周日)' },
  { type: 1, text: '周一' },
  { type: 2, text: '周二' },
  { type: 3, text: '周三' },
  { type: 4, text: '周四' },
  { type: 5, text: '周五' },
  { type: 6, text: '周六' },
  { type: 7, text: '周日' },
])

// 修改配送时间
const onChangeDelivery = (event: UniHelper.SelectorPickerOnChangeEvent, index: number) => {
  post_order_info.value![index].delivery_time = event.detail.value
}
// 如果有params.num说明是从详情页点击立即购买跳转过来的，而这个num并没有传递给后端，
// 所以做一个判断，是否需要修改为params.id
const get_goods_sku_info_byid = async (sku_id_list: number[]) => {
  console.log('触发获取商品sku信息')
  console.log(sku_id_list)
  // 有ordernumber说明是从再来一单过来的
  let res = [] as any
  if (params.order_number) {
    res = await getSkuByOrderNumberAPI(params.order_number)
    console.log('通过订单号获取sku')
    console.log(res.data)
    skuOrderData.value = res.data
    skuOrderData.value.forEach((item) => {
      // 后续可改变数量的返回方式，为了后续方便修改，暂时这么处理
      if (defaultAddress.value) {
        post_order_info.value!.push({
          sku: item.id,
          num: params.num ? params.num : item.cart_sku_num,
          remark: '',
          delivery_time: 0,
          address: defaultAddress.value.id as number,
        })
      }
    })
  } else {
    res = await getSkuByIdApi(sku_id_list)
    skuOrderData.value = res.data!
    // 直接把数据映射出来，给post_order_info，这个数据直接作为数据传递给后端创建订单
    skuOrderData.value.forEach((item) => {
      if (defaultAddress.value) {
        post_order_info.value!.push({
          sku: item.id,
          num: params.num ? params.num : item.cart_sku_num,
          remark: '',
          delivery_time: 0,
          address: defaultAddress.value.id as number,
        })
      }
    })
  }
}

onLoad(async () => {
  const res = await getAddressListAPI()
  addressListData.value = res.data
  // 如果有订单号号说明是再次购买

  await get_goods_sku_info_byid(params.sku_id_list)

  // 如果有params.num,就说明是从商品详情页跳转过来的，商品详情页跳转必定只有一个商品，
  // 并且数量以跳转前传递的数量为准,因为详情页跳转过来的商品数量是动态的
})
const defaultAddress = computed(() => {
  if (addressListData.value?.length) {
    const defaultAddress = addressListData.value.find((item) => item.default)
    if (addressStore.address.id) {
      return addressStore.address
    } else if (defaultAddress) {
      return defaultAddress as addressType
    }
  }
  return false
})

const checkAddress = () => {
  uni.navigateTo({ url: '/SubPackages/address/address?check=true' })
}
const total_price = computed(() => {
  let total_price = 0
  skuOrderData.value.forEach((item) => {
    if (!item.cart_sku_num) {
      item.cart_sku_num = params.num
    }
    total_price += item.price * 100 * item.cart_sku_num
    //
  })
  return (total_price / 100).toFixed(2) // 转换回元单位，保留2位小数
})
const total_freight = computed(() => {
  let total_freight = 0
  skuOrderData.value.forEach((item) => {
    total_freight += item.freight * 100 * item.cart_sku_num
  })
  return (total_freight / 100).toFixed(2)
})

// 算上运费的价格
const total_freight_price = computed(() => {
  let total_freight_price = 0
  total_freight_price = Number(total_freight.value) * 100 + Number(total_price.value) * 100
  return (total_freight_price / 100).toFixed(2)
})

// 深度监听计算属性，defaultAddress，一旦defaultaddress中的数据发生变化，
// 便把需要提交给后端的post_order_info中的地址id修改为defaultaddress的地址id
watch(
  () => defaultAddress.value,
  (newValue, oldValue) => {
    if (newValue) {
      post_order_info.value.forEach((item) => {
        item.address = newValue.id as number
      })
    }
  },
  { deep: true },
)

// 提交订单
const submit = async () => {
  if (!defaultAddress.value) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none',
    })
    return
  }
  const res = await createOrderApi(post_order_info.value)

  if (res.code === 200) {
    uni.showToast({
      title: '创建订单成功',
      icon: 'none',
    })
    setTimeout(() => {
      // 使用uni.redirectTo()方法，跳转到订单详情页，这样页面栈中就只剩下订单详情页了，
      if (res.data instanceof Array) {
        uni.redirectTo({
          url: '/pages/order/components/orderDetail?order_number=' + res.data?.[0].order_number,
        })
      } else {
        uni.redirectTo({
          url: '/pages/order/components/orderDetail?order_number=' + res.data!.order_number,
        })
      }
    }, 1000)
  } else {
    uni.showToast({
      title: `${res.message}`,
      icon: 'none',
    })
  }
}
</script>

<template>
  <scroll-view scroll-y class="viewport">
    <!-- 收货地址 -->
    <navigator
      v-if="defaultAddress"
      class="shipment"
      hover-class="none"
      url="/SubPackages/address/address?check=true"
    >
      <view class="user"> {{ defaultAddress.name }} {{ defaultAddress.telephone }} </view>
      <view class="address"
        >{{ defaultAddress.province }} {{ defaultAddress.city }} {{ defaultAddress.district }}
        {{ defaultAddress.address }}</view
      >
      <text class="icon icon-right"></text>
    </navigator>
    <navigator
      v-else
      class="shipment"
      hover-class="none"
      url="/SubPackages/address/address?check=true"
    >
      <view class="address" @tap="checkAddress"> 请选择收获地址 </view>
      <text class="icon icon-right"></text>
    </navigator>

    <!-- 商品信息 -->
    <view class="goods" v-for="(item, index) in skuOrderData" :key="item.id">
      <navigator
        :url="`/pages/goods/goods?goods_id=${item.product}`"
        class="item"
        hover-class="none"
      >
        <image
          class="picture"
          src="https://yanxuan-item.nosdn.127.net/c07edde1047fa1bd0b795bed136c2bb2.jpg"
        />
        <view class="meta">
          <view class="name ellipsis"> {{ item.goods_name }} </view>
          <view class="attrs">{{ item.sku_name_arr.join(' ') }}</view>
          <view class="prices">
            <view class="pay-price symbol">{{ item.price }}</view>
            <view class="price symbol">{{ item.original_price }}</view>
          </view>
          <view class="count">{{ params.num ? params.num : item.cart_sku_num }}</view>
        </view>
      </navigator>
      <!-- 配送及支付方式 -->
      <view class="related">
        <view class="item">
          <text class="text">配送时间</text>
          <picker :range="deliveryList" range-key="text" @change="onChangeDelivery($event, index)">
            <!-- 当选项发生改变时修改需要提交给后端的订单数据对象，
             post_order_info[index].delivery_time是选中后所修改的数据。而这个数据可以用作索引来显示对应的文本 -->
            <view class="icon-fonts picker">{{
              deliveryList[post_order_info[index].delivery_time].text
            }}</view>
          </picker>
        </view>
        <view class="item">
          <text class="text">订单备注</text>
          <input
            class="input"
            :cursor-spacing="30"
            placeholder="选题，建议留言前先与商家沟通确认"
            v-model="post_order_info![index].remark"
          />
        </view>
      </view>
    </view>

    <!-- 支付金额 -->
    <view class="settlement">
      <view class="item">
        <text class="text">商品总价: </text>
        <text class="number symbol">{{ total_price }}</text>
      </view>
      <view class="item">
        <text class="text">运费: </text>
        <text class="number symbol">{{ total_freight }}</text>
      </view>
    </view>
  </scroll-view>

  <!-- 吸底工具栏 -->
  <view class="toolbar" :style="{ paddingBottom: systemInfo.safeAreaInsets?.bottom + 'px' }">
    <view class="total-pay symbol">
      <text class="number">{{ total_freight_price }}</text>
    </view>
    <view class="button" :class="{ disabled: !defaultAddress }" @tap="submit"> 提交订单 </view>
  </view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}

.symbol::before {
  content: '¥';
  font-size: 80%;
  margin-right: 5rpx;
}

.shipment {
  margin: 20rpx;
  padding: 30rpx 30rpx 30rpx 84rpx;
  font-size: 26rpx;
  border-radius: 10rpx;
  background: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/locate.png)
    20rpx center / 50rpx no-repeat #fff;
  position: relative;

  .icon {
    font-size: 36rpx;
    color: #333;
    transform: translateY(-50%);
    position: absolute;
    top: 50%;
    right: 20rpx;
  }

  .user {
    color: #333;
    margin-bottom: 5rpx;
  }

  .address {
    color: #666;
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    padding: 30rpx 0;
    border-top: 1rpx solid #eee;

    &:first-child {
      border-top: none;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrs {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .prices {
      display: flex;
      align-items: baseline;
      margin-top: 6rpx;
      font-size: 28rpx;

      .pay-price {
        margin-right: 10rpx;
        color: #cf4444;
      }

      .price {
        font-size: 24rpx;
        color: #999;
        text-decoration: line-through;
      }
    }

    .count {
      position: absolute;
      bottom: 0;
      right: 0;
      font-size: 26rpx;
      color: #444;
    }
  }
}

.related {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .input {
    flex: 1;
    text-align: right;
    margin: 20rpx 0;
    padding-right: 20rpx;
    font-size: 26rpx;
    color: #999;
  }

  .item .text {
    width: 125rpx;
  }

  .picker {
    color: #666;
  }

  .picker::after {
    content: '\e6c2';
  }
}

/* 结算清单 */
.settlement {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    font-size: 26rpx;
    color: #333;
  }

  .danger {
    color: #cf4444;
  }
}

/* 吸底工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx;
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .total-pay {
    font-size: 40rpx;
    color: #cf4444;

    .decimal {
      font-size: 75%;
    }
  }

  .button {
    width: 220rpx;
    text-align: center;
    line-height: 72rpx;
    font-size: 26rpx;
    color: #fff;
    border-radius: 72rpx;
    background-color: #27ba9b;
  }

  .disabled {
    opacity: 0.6;
  }
}
</style>
